package top.lightHearted.controller;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

/**
 * UserController class
 *
 * @author gpf
 * @date 2018/03/26
 */
@Controller
public class UserController {


    @Autowired
    private JmsTemplate jmsTemplate;

    @RequestMapping(value = "/testSend", method = RequestMethod.GET)
    public String send(){
        broadcastToTopic("SYSTEM.UPDATE", "测试topic");
        return null;
    }

    /**
     * 广播/订阅
     */
    public void broadcastToTopic(String topic, String message) {


        Topic destination = new ActiveMQTopic(topic);
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public javax.jms.Message createMessage(Session sess) throws JMSException {
                TextMessage msg = sess.createTextMessage(message);
                return msg;
            }
        });
    }

}
